package callcenter.dao;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceException;
import javax.persistence.Query;

import util.CustomExcepcion;
import callcenter.model.Agent;
import callcenter.model.SessionType;


@LocalBean
@Stateless
public class AgentDao implements Serializable {
	
	
	private static final long serialVersionUID = 1L;

	@PersistenceContext(name = "CCenterEJB", unitName = "CCenterEJB")
	EntityManager em;

	public Agent findAgent(Integer userId, String username) throws CustomExcepcion {

		try {
			Query q = em
					.createQuery("SELECT a.id,a.autoready,a.code "
							+ "FROM Agent a " + "WHERE a.userId = :userId");

			q.setParameter("userId", userId);

			Object[] agentObject = (Object[]) q.getSingleResult();

			Integer id = (Integer) agentObject[0];
			Boolean autoready = (Boolean) agentObject[1];
			String code = (String) agentObject[2];
			

			Agent agent = new Agent();
			agent.setId(id);
			agent.setAutoready(autoready);
			agent.setCode(code);
			

			return agent;

		} catch (NoResultException e) {
			throw new CustomExcepcion("No se encontr� agente para "
					+ username);
		} catch (Exception e) {
			throw new CustomExcepcion(e.getMessage());
		}

	}
	
	public Agent findAgentById(Integer agentId) throws CustomExcepcion {

		try {
			Query q = em
					.createQuery("SELECT a.id,a.autoready,a.code "
							+ "FROM Agent a " + "WHERE a.id = :agentId");

			q.setParameter("agentId", agentId);

			Object[] agentObject = (Object[]) q.getSingleResult();

			Integer id = (Integer) agentObject[0];
			Boolean autoready = (Boolean) agentObject[1];
			String code = (String) agentObject[2];
			

			Agent agent = new Agent();
			agent.setId(id);
			agent.setAutoready(autoready);
			agent.setCode(code);
			
			return agent;

		} catch (NoResultException e) {
			throw new CustomExcepcion("No se encontr� agente con id="
					+ agentId);
		} catch (Exception e) {
			throw new CustomExcepcion(e.getMessage());
		}

	}
	



	

}
